import {
  QuotesCallback,
  ResolutionBackValues,
  HistoryDepth,
  LibrarySymbolInfo,
  GetMarksCallback,
  Mark,
  TimescaleMark,
  ServerTimeCallback,
  SearchSymbolsCallback,
  ResolveCallback,
  ErrorCallback,
  HistoryCallback,
  SubscribeBarsCallback,
  DomeCallback,
  OnReadyCallback,
  DatafeedClass,
  Bar,
} from "@@/components/common/CtradingView";
import dayjs from "dayjs";
import { apiWkcUsdtKline, ApiWkcUsdtKline } from "@@/api/module/tabbarPage";

export class Datafee implements DatafeedClass {
  /**图表数据 */
  public data: ApiWkcUsdtKline.DataItem[] = [];
  /**可选时间 */
  public supported_resolutions: ["1", "15", "60", "240", "1D", "1W"] = [
    "1",
    "15",
    "60",
    "240",
    "1D",
    "1W",
  ];
  public symbol = "WKC";
  interval: TupleToUnion<typeof this.supported_resolutions> = undefined as any;
  getInterval(time = this.interval) {
    if (time === "1D") return 1440;
    if (time === "1W") return 1440 * 7;
    return Number(time);
  }
  /**商品信息https://zlq4863947.gitbook.io/tradingview/3-shu-ju-bang-ding/symbology */
  public symbolInfo: LibrarySymbolInfo & AnyObject = {
    symbol: this.symbol,
    name: this.symbol,
    full_name: this.symbol,
    timezone: "Asia/Shanghai",
    minmov: 1,
    /**休市时间 https://zlq4863947.gitbook.io/tradingview/3-shu-ju-bang-ding/trading-sessions*/
    session: "24x7",
    // session: "0930-1630",
    has_intraday: true, //标志符是否支持低于日线的时间周期，如1分钟、5分钟、15分钟等。
    has_no_volume: false, //数据是否包含交易量
    has_daily: false, //交易标志符是否支持日线时间周期。
    has_weekly_and_monthly: true, //交易标志符是否支持周线和月线时间周期。
    description: this.symbol,
    type: this.symbol,
    /**https://zlq4863947.gitbook.io/tradingview/fu-lu/resolution */
    supported_resolutions: this.supported_resolutions,
    pricescale: 100000,
    ticker: "stock",
    exchange: "",
    listed_exchange: this.symbol,
  };

  onReady(callback: OnReadyCallback) {
    callback({
      supports_marks: true,
      supports_timescale_marks: true,
      supports_time: true,
      exchanges: [{ value: "", name: "ALL", desc: "" }],
      symbols_types: [{ name: this.symbol, value: this.symbol }],
      supported_resolutions: this.supported_resolutions,
    });
  }
  /**解决标志 */
  resolveSymbol(
    symbolName: string,
    onResolve: ResolveCallback,
    onError: ErrorCallback
  ): void {
    console.log("resolveSymbol");
    setTimeout(() => {
      onResolve(this.symbolInfo);
    }, 0);
  }
  public async getData(interval: typeof this.interval) {
    if (interval === this.interval) return [];
    const res = await apiWkcUsdtKline({
      interval: this.getInterval(interval),
    });
    if (res.code !== 200) return res.msg;
    this.interval = interval;
    this.data = res.data;
    return this.data;
  }
  /**获取图表数据 */
  async getBars(
    symbolInfo: LibrarySymbolInfo,
    /**时间选项 */
    resolution: typeof this.interval,
    /**时间范围(大) */
    rangeStartDate: number,
    /**时间范围(小) */
    rangeEndDate: number,
    onResult: HistoryCallback,
    onError: ErrorCallback,
    isFirstCall: boolean
  ) {
    const timeRange = [rangeStartDate * 1000, rangeEndDate * 1000];
    console.log(
      `获取图表数据${dayjs(timeRange[0]).format(
        "YYYY-MM-DD HH:mm:ss"
      )}到${dayjs(timeRange[1]).format("YYYY-MM-DD HH:mm:ss")}`
    );
    if (timeRange[0] > timeRange[1]) timeRange.reverse();
    const res = await this.getData(resolution);
    if (typeof res === "string") return onError(res);
    const data = this.data.filter(
      (v) => v.time >= timeRange[0] && v.time <= timeRange[1]
    );

    console.log("数据长度", data.length);
    if (data.length) return onResult(data, { noData: false });
    if (
      timeRange[0] < this.data[0]?.time ||
      timeRange[1] > this.data[this.data.length - 1]?.time
    ) {
      console.log("完成数据加载");
      return onResult([], { noData: true });
    }
    return onResult([], { noData: true, nextTime: 1000 });
  }
  /**搜索图表 */
  searchSymbols(
    userInput: string,
    exchange: string,
    symbolType: string,
    onResult: SearchSymbolsCallback
  ): void {
    onResult([this.symbolInfo as any]);
  }
  subscribeBars(
    symbolInfo: LibrarySymbolInfo,
    resolution: typeof this.interval,
    onTick: SubscribeBarsCallback,
    listenerGuid: string,
    onResetCacheNeededCallback: () => void
  ): void {
    console.log("subscribeBars");
  }
  unsubscribeBars(listenerGuid: string): void {
    console.log("unsubscribeBars");
  }
  getQuotes(
    symbols: string[],
    onDataCallback: QuotesCallback,
    onErrorCallback: (msg: string) => void
  ): void {
    console.log("getQuotes");
    onErrorCallback("");
  }
  subscribeQuotes(
    symbols: string[],
    fastSymbols: string[],
    onRealtimeCallback: QuotesCallback,
    listenerGUID: string
  ): void {
    console.log("subscribeQuotes");
  }
  unsubscribeQuotes(listenerGUID: string): void {
    console.log("unsubscribeQuotes");
  }
  calculateHistoryDepth?(
    resolution: typeof this.interval,
    resolutionBack: ResolutionBackValues,
    intervalBack: number
  ): HistoryDepth | undefined {
    console.log("calculateHistoryDepth");
    return undefined;
  }
  /**获取蜡烛图标记 */
  getMarks?(
    symbolInfo: LibrarySymbolInfo,
    from: number,
    to: number,
    onDataCallback: GetMarksCallback<Mark>,
    resolution: typeof this.interval
  ): void {
    console.log("获取蜡烛图标记");
    onDataCallback([]);
  }
  /**获取底部柱状图标记 */
  getTimescaleMarks?(
    symbolInfo: LibrarySymbolInfo,
    from: number,
    to: number,
    onDataCallback: GetMarksCallback<TimescaleMark>,
    resolution: typeof this.interval
  ): void {
    console.log("获取底部柱状图标记");
    onDataCallback([]);
  }
  /**获取服务器时间 */
  getServerTime?(callback: ServerTimeCallback): void {
    console.log("获取服务器时间");
    callback(dayjs().valueOf());
  }
  subscribeDepth?(
    symbolInfo: LibrarySymbolInfo,
    callback: DomeCallback
  ): string {
    console.log("subscribeDepth");
    return "";
  }
  unsubscribeDepth?(subscriberUID: string): void {
    console.log("unsubscribeDepth");
  }
}
